package com.bdmc.common.utils.wechat;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bdmc.common.config.BdmcConfig;
import com.bdmc.common.constant.Constants;
import com.bdmc.common.utils.RedisUtils;
import com.bdmc.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class WeChatMiniUtil {

    private static final String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    protected static Logger logger = LoggerFactory.getLogger(WeChatMiniUtil.class);



    // @Autowired
    // HttpUtils httpClient;

    /**
     * 获取微信小程序的accesstoken
     *
     * @return accesstoken
     */
    public String getAccessToken() {
        AccessToken accessToken = null;

        String redisToken = RedisUtils.getCacheObject(WXConfig.MINI_ACCESS_TOKEN);
        if (StringUtils.isNotEmpty(redisToken)) {
            return redisToken;
        }
        String requestUrl = access_token_url.replace("APPID", WXConfig.xappid).replace("APPSECRET",
                WXConfig.xappSecret);
        String getResult = HttpUtil.get(requestUrl);
        if (StringUtils.isEmpty(getResult)) {
            return null;
        }
        JSONObject jsonObject = JSONUtil.parseObj(requestUrl);
        // 如果请求成功
        try {
            accessToken = new AccessToken();
            accessToken.setToken(jsonObject.getStr("access_token"));
            accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
            Integer diff = (accessToken.getExpiresIn() - 5 * 60);// 设置提前5分钟过期token
			RedisUtils.setCacheObject(WXConfig.MINI_ACCESS_TOKEN, accessToken.getToken(), diff, TimeUnit.SECONDS);
            return accessToken.getToken();
        } catch (Exception e) {
            // 获取token失败
            logger.info("获取token失败 errcode:{} errmsg:{}" + jsonObject.getInt("errcode")
                    + jsonObject.getStr("errmsg"));
        }
        return null;
    }

    /**
     * 调用code2session
     *
     * @param jscode jscode
     * @return OAuthOpenid
     */
    public OAuthOpenid GetWXOpenidInfo(String jscode){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WXConfig.xappid + "&secret="
                + WXConfig.xappSecret + "&js_code=" + jscode + "&grant_type=authorization_code";

        String getResult = HttpUtil.get(url);
        OAuthOpenid oAuth = JSONUtil.toBean(getResult, OAuthOpenid.class);
        if (StringUtils.isNotEmpty(oAuth.getSession_key())) {
            RedisUtils.setCacheMapValue(WXConfig.MINI_SESSION_KEY, oAuth.getOpenid(), oAuth.getSession_key());
        }
        return oAuth;
    }

    /**
     * 解密微信手机号
     *
     * @param encryptedData 加密数据
     * @param sessionKey    微信用户登录的sessionkey
     * @param iv            向量
     * @return mobile
     */
    public String decryptPhoneNumber(String encryptedData, String sessionKey, String iv) {
        AESForWeixinGetPhoneNumber aes = new AESForWeixinGetPhoneNumber(encryptedData, sessionKey, iv);
        WeixinPhoneDecryptInfo info = aes.decrypt();
        String mobile = "";
        if (null == info) {
            logger.error("手机号解密错误");
        } else {
            if (!info.getWeixinWaterMark().getAppid().equals(WXConfig.xappid)) {
                System.out.println("wrong appId");
            }
            mobile = info.getPhoneNumber();
            System.out.println(info.toString());
        }
        return mobile;
    }

    /**
     * 下载微信图片到本地
     *
     * @param media_id 微信图片资源id
     * @return 本地服务器图片路径
     */
//    public String downloadImage(String media_id) {
//        // 获取accesstoken（可根据情况自行获取accesstoken）
//        String token = getAccessToken();
//        String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + token + "&media_id=" + media_id;
//        RestTemplate restTemplate = new RestTemplate();
//        // 进行网络请求,访问url接口
//        ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, byte[].class);
//        // 解析返回值（请求成功返回图片二进制流，失败返回错误信息json）
//        if (responseEntity.getStatusCode() == HttpStatus.OK) {
//            byte[] sessionData = responseEntity.getBody();
//            try {
//                for (int i = 0; i < Objects.requireNonNull(sessionData).length; ++i) {
//                    if (sessionData[i] < 0) {// 调整异常数据
//                        sessionData[i] += 256;
//                    }
//                }
//
//                File path = new File(BdmcConfig.getUploadPath());
//                if (!path.exists()) {
//                    path.mkdir();
//                }
//                // 生成jpg图片
//                String savePath = path.getAbsolutePath() + "/image/";// 新生成的图片
//                File path1 = new File(savePath);
//                if (!path1.exists()) {
//                    path1.mkdir();
//                }
//                // 根据内容类型获取扩展名
//                String fileExt = responseEntity.getHeaders().getContentType().getSubtype();
//                // 将mediaId作为文件名
//                String filePath = savePath + media_id + "." + fileExt;
//                OutputStream out = new FileOutputStream(filePath);
//                out.write(sessionData);
//                out.flush();
//                out.close();
//                return BdmcConfig.getUploadPath() + "/image/" + media_id + "." + fileExt;
//            } catch (Exception e) {
//                System.out.println(e.getMessage());
//                return null;
//            }
//        } else {
//            return null;
//        }
//
//    }

    /**
     * 发送告警消息
     * @param openid openid
     * @param simCard simcard
     * @param alarmType alarmType
     * @param deviceName deviceName
     * @param location location
     * @param remark remark
     * @return result
     */
    public String SendDeviceAlarmTemplateMsg(String openid,String simCard,String alarmType, String deviceName, String location, String remark) {
        TemplateData character_string1 = new TemplateData(simCard, "");
        TemplateData thing2 = new TemplateData(alarmType, "");
        TemplateData thing3 = new TemplateData(deviceName, "");
        TemplateData thing4 = new TemplateData(location, "");
        TemplateData thing5 = new TemplateData(remark, "");
        Map<String, TemplateData> data = new HashMap<>();
        data.put("character_string1", character_string1);
        data.put("thing2", thing2);
        data.put("thing3", thing3);
        data.put("thing4", thing4);
        data.put("thing5", thing5);
        String result = sendTemplateMessage(openid,data,simCard);
        logger.info(result);
        return result;

    }

    /**
     * 给小程序发送模版消息
     * @param openid 用户openid
     * @param data 模版里的数据内容
     * @return
     */
    public String sendTemplateMessage(String openid, Map<String, TemplateData> data,String simCard) {
        String token = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+token;
        WechatMiniTemplate tmp = new WechatMiniTemplate();
        tmp.setTouser(openid);
        //tmp.setMiniprogram_state("developer");//开发版，发布前注释
        tmp.setTemplate_id(WXConfig.alarm_push_template);
        tmp.setPage("/pages/tabbar/index/index?simCard="+simCard);
        tmp.setData(data);
        return HttpUtil.post(url, JSONUtil.toJsonStr(tmp));
    }

}
